import * as childProcess from 'child_process';
import * as vscode from 'vscode';
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';

export function DebugSign(context: vscode.ExtensionContext, DevEcoPath: string) {
    let pluginName = path.basename(context.extensionPath);

    let cacheDir = path.join(os.homedir(), '.cache', pluginName);
    if (!fs.existsSync(cacheDir)) {
        fs.mkdirSync(cacheDir, { recursive: true });
    }
    
    let keystorePath = path.join(cacheDir, 'vscodedemokey.p12');
    let csrPath = path.join(cacheDir, 'vscodedemokey.csr');
    let alias = 'vscode_demo_app';
    let storepassAndKeypass = 'vscode_openharmony';
    let command1 = `"${DevEcoPath}/jbr/jre/bin/keytool" -genkeypair -alias "${alias}" -keyalg EC -sigalg SHA256withECDSA -dname "C=CN,O=Test,OU=Test IDE,CN=vscode_demo_app" -keystore "${keystorePath}" -storetype pkcs12 -validity 9125 -storepass "${storepassAndKeypass}" -keypass "${storepassAndKeypass}"`;
    let command2 = `${DevEcoPath}/jbr/jre/bin/keytool -certreq -alias "${alias}" -keystore ${keystorePath} -storetype pkcs12 -file ${csrPath}`;

    childProcess.exec(command1, (error) => {
        if (error) {
            vscode.window.showErrorMessage(`Error executing command: ${error.message}`);
            return;
        }

        childProcess.exec(command2, (error) => {
            if (error) {
                vscode.window.showErrorMessage(`Error executing command: ${error.message}`);
                return;
            }

            vscode.window.showInformationMessage('Key pair and CSR generated successfully!');
        });
    });
}